<template>
	<div>
		<el-row :gutter="15">
<el-form ref="elForm" :model="dataForm" :rules="dataRule" size="small" label-width="100px" label-position="right"  :disabled="setting.readonly" >
<template v-if="!loading && formOperates">
			<el-col :span="24"    v-if="judgeShow('code')" >
				<el-form-item  label="单据号"   prop="code" >
					<el-input  v-model="dataForm.code" placeholder="系统自动生成" :disabled="true"  clearable  :style='{"width":"100%"}'>

                </el-input>
                </el-form-item>
            </el-col>
			<el-col :span="24"    v-if="judgeShow('billdate')" >
				<el-form-item  label="单据日期"   prop="billdate" >
					<jnpf-open-data  v-model="dataForm.billdate" readonly   :disabled="judgeWrite('billdate')"   type="currTime" >

                </jnpf-open-data>
                </el-form-item>
            </el-col>
			<el-col :span="24"    v-if="judgeShow('billmaker')" >
				<el-form-item  label="制单人"   prop="billmaker" >
					<jnpf-open-data  v-model="dataForm.billmaker" readonly   :disabled="judgeWrite('billmaker')"   type="currUser" >

                </jnpf-open-data>
                </el-form-item>
            </el-col>
			<el-col :span="24"    v-if="judgeShow('status')" >
				<el-form-item  label="单据状态"   prop="status" >
					<el-select  v-model="dataForm.status" placeholder="请选择" :disabled="true"  clearable  :style='{"width":"100%"}'>
                            <el-option v-for="(item, index) in statusOptions" :key="index" :label="item.fullName" :value="item.id" :disabled="item.disabled" ></el-option>

                </el-select>
                </el-form-item>
            </el-col>
			<el-col :span="24"    v-if="judgeShow('approver')" >
				<el-form-item  label="审批人"   prop="approver" >
					<user-select  v-model="dataForm.approver" placeholder="请选择" :disabled="true"  clearable >

                </user-select>
                </el-form-item>
            </el-col>
			<el-col :span="24"    v-if="judgeShow('approvetime')" >
				<el-form-item  label="审批时间"   prop="approvetime" >
					<el-date-picker  v-model="dataForm.approvetime" placeholder="请选择" :disabled="true"  clearable  :style='{"width":"100%"}' type="datetime"  format="yyyy-MM-dd HH:mm:ss"  value-format="timestamp" >

                </el-date-picker>
                </el-form-item>
            </el-col>
			<el-col :span="24"    v-if="judgeShow('attachment')" >
				<el-form-item  label="附件上传"   prop="attachment" >
					<JNPF-UploadFz  v-model="dataForm.attachment" :fileSize="10"     :disabled="judgeWrite('attachment')"   sizeUnit="MB"  :limit="9"  buttonText="点击上传" >

                </JNPF-UploadFz>
                </el-form-item>
            </el-col>
			<el-col :span="24"    v-if="judgeShow('creatoruserid')" >
				<el-form-item  label="创建用户"   prop="creatoruserid" >
					<jnpf-open-data  v-model="dataForm.creatoruserid" readonly   :disabled="judgeWrite('creatoruserid')"   type="currUser" >

                </jnpf-open-data>
                </el-form-item>
            </el-col>
			<el-col :span="24"    v-if="judgeShow('creatortime')" >
				<el-form-item  label="创建时间"   prop="creatortime" >
					<jnpf-open-data  v-model="dataForm.creatortime" readonly   :disabled="judgeWrite('creatortime')"   type="currTime" >

                </jnpf-open-data>
                </el-form-item>
            </el-col>
			<el-col :span="24"    v-if="judgeShow('lastmodifyuserid')" >
				<el-form-item  label="修改用户"   prop="lastmodifyuserid" >
					<el-input  v-model="dataForm.lastmodifyuserid" placeholder="系统自动生成"  readonly   :disabled="judgeWrite('lastmodifyuserid')"  >

                </el-input>
                </el-form-item>
            </el-col>
			<el-col :span="24"    v-if="judgeShow('lastmodifytime')" >
				<el-form-item  label="修改时间"   prop="lastmodifytime" >
					<el-input  v-model="dataForm.lastmodifytime" placeholder="系统自动生成"  readonly   :disabled="judgeWrite('lastmodifytime')"  >

                </el-input>
                </el-form-item>
            </el-col>
			<el-col :span="24" v-if="judgeShow('gyplanbList') && formOperates">
				<el-form-item label-width="0">
					<div class="JNPF-common-title">
						<h2>计划基本信息</h2>
					</div>
    <el-table :data="dataForm.gyplanbList" size='mini'   >
						<el-table-column type="index" width="50" label="序号" align="center" />
			<el-table-column prop="zid" label="采购计划主表主键"   v-if="judgeShow('gyplanbList-zid')"  >
				<template slot="header" v-if="judgeRequired('gyplanbList-zid')">
					<span class="required-sign">*</span>采购计划主表主键
				</template>
				<template slot-scope="scope">
					<el-input   v-model="scope.row.zid"  placeholder="请输入"   :disabled="judgeWrite('gyplanbList') || judgeWrite('gyplanbList-zid')"    clearable  :style='{"width":"100%"}'>
				</el-input>
		</template>
		</el-table-column>
			<el-table-column prop="material" label="物料名称"   v-if="judgeShow('gyplanbList-material')"  >
				<template slot="header" v-if="judgeRequired('gyplanbList-material')">
					<span class="required-sign">*</span>物料名称
				</template>
				<template slot-scope="scope">
					<popupSelect   v-model="scope.row.material"  placeholder="请选择"   :disabled="judgeWrite('gyplanbList') || judgeWrite('gyplanbList-material')"    clearable  :field="'material'+scope.$index"  interfaceId="372311571319229701" :columnOptions="gyplanbmaterialcolumnOptions" propsValue="F_Id" relationField="F_MatName" popupType="dialog"
 popupTitle="选择数据"   popupWidth="60%"
  >
				</popupSelect>
		</template>
		</el-table-column>
			<el-table-column prop="" label="物料型号"   >
				<template slot="header" v-if="judgeRequired('gyplanbList-')">
					<span class="required-sign">*</span>物料型号
				</template>
				<template slot-scope="scope">
					<popupAttr      :relationField="'material'+scope.$index"  showField="F_MatSpec" >
				</popupAttr>
		</template>
		</el-table-column>
			<el-table-column prop="" label="物料编码"   >
				<template slot="header" v-if="judgeRequired('gyplanbList-')">
					<span class="required-sign">*</span>物料编码
				</template>
				<template slot-scope="scope">
					<popupAttr      :relationField="'material'+scope.$index"  showField="F_MatCode" >
				</popupAttr>
		</template>
		</el-table-column>
			<el-table-column prop="supplier" label="供应商编码"   v-if="judgeShow('gyplanbList-supplier')"  >
				<template slot="header" v-if="judgeRequired('gyplanbList-supplier')">
					<span class="required-sign">*</span>供应商编码
				</template>
				<template slot-scope="scope">
					<popupSelect   v-model="scope.row.supplier"  placeholder="请选择"   :disabled="judgeWrite('gyplanbList') || judgeWrite('gyplanbList-supplier')"    clearable  :field="'supplier'+scope.$index"  interfaceId="372402284212000325" :columnOptions="gyplanbsuppliercolumnOptions" propsValue="F_Id" relationField="F_Code" popupType="dialog"
 popupTitle="选择数据"   popupWidth="800px"
  >
				</popupSelect>
		</template>
		</el-table-column>
			<el-table-column prop="" label="供应商名称"   >
				<template slot="header" v-if="judgeRequired('gyplanbList-')">
					<span class="required-sign">*</span>供应商名称
				</template>
				<template slot-scope="scope">
					<popupAttr      :relationField="'supplier'+scope.$index"  showField="F_Name" >
				</popupAttr>
		</template>
		</el-table-column>
			<el-table-column prop="number" label="数量"   v-if="judgeShow('gyplanbList-number')"  >
				<template slot="header" v-if="judgeRequired('gyplanbList-number')">
					<span class="required-sign">*</span>数量
				</template>
				<template slot-scope="scope">
					<el-input-number   v-model="scope.row.number"  placeholder="数字文本"   :disabled="judgeWrite('gyplanbList') || judgeWrite('gyplanbList-number')"    :step="1" >
				</el-input-number>
		</template>
		</el-table-column>
			<el-table-column prop="price" label="单价"   v-if="judgeShow('gyplanbList-price')"  >
				<template slot="header" v-if="judgeRequired('gyplanbList-price')">
					<span class="required-sign">*</span>单价
				</template>
				<template slot-scope="scope">
					<el-input-number   v-model="scope.row.price"  placeholder="数字文本"   :disabled="judgeWrite('gyplanbList') || judgeWrite('gyplanbList-price')"    :step="1" >
				</el-input-number>
		</template>
		</el-table-column>
			<el-table-column prop="money" label="金额"   v-if="judgeShow('gyplanbList-money')"  >
				<template slot="header" v-if="judgeRequired('gyplanbList-money')">
					<span class="required-sign">*</span>金额
				</template>
				<template slot-scope="scope">
					<el-input-number   v-model="scope.row.money"  placeholder="数字文本" :disabled="true"  :step="1"  controls-position='right' >
				</el-input-number>
		</template>
		</el-table-column>
			<el-table-column prop="needtime" label="需求时间"   v-if="judgeShow('gyplanbList-needtime')"  >
				<template slot="header" v-if="judgeRequired('gyplanbList-needtime')">
					<span class="required-sign">*</span>需求时间
				</template>
				<template slot-scope="scope">
					<el-date-picker   v-model="scope.row.needtime"  placeholder="请选择"   :disabled="judgeWrite('gyplanbList') || judgeWrite('gyplanbList-needtime')"    clearable  :style='{"width":"100%"}' type="date"  format="yyyy-MM-dd"  value-format="timestamp" >
				</el-date-picker>
		</template>
		</el-table-column>
			<el-table-column prop="userman" label="使用人"   v-if="judgeShow('gyplanbList-userman')"  >
				<template slot="header" v-if="judgeRequired('gyplanbList-userman')">
					<span class="required-sign">*</span>使用人
				</template>
				<template slot-scope="scope">
					<user-select   v-model="scope.row.userman"  placeholder="请选择"   :disabled="judgeWrite('gyplanbList') || judgeWrite('gyplanbList-userman')"    clearable >
				</user-select>
		</template>
		</el-table-column>
			<el-table-column prop="userdept" label="使用部门"   v-if="judgeShow('gyplanbList-userdept')"  >
				<template slot="header" v-if="judgeRequired('gyplanbList-userdept')">
					<span class="required-sign">*</span>使用部门
				</template>
				<template slot-scope="scope">
					<dep-select   v-model="scope.row.userdept"  placeholder="请选择"   :disabled="judgeWrite('gyplanbList') || judgeWrite('gyplanbList-userdept')"    clearable >
				</dep-select>
		</template>
		</el-table-column>
			<el-table-column prop="plannum" label="实施计划号"   v-if="judgeShow('gyplanbList-plannum')"  >
				<template slot="header" v-if="judgeRequired('gyplanbList-plannum')">
					<span class="required-sign">*</span>实施计划号
				</template>
				<template slot-scope="scope">
					<popupSelect   v-model="scope.row.plannum"  placeholder="请选择"   :disabled="judgeWrite('gyplanbList') || judgeWrite('gyplanbList-plannum')"    clearable  :field="'plannum'+scope.$index"  interfaceId="372403859915544133" :columnOptions="gyplanbplannumcolumnOptions" propsValue="F_Id" relationField="F_PlanCode" popupType="dialog"
 popupTitle="选择数据"   popupWidth="800px"
  >
				</popupSelect>
		</template>
		</el-table-column>
			<el-table-column prop="purchaser" label="采购员"   v-if="judgeShow('gyplanbList-purchaser')"  >
				<template slot="header" v-if="judgeRequired('gyplanbList-purchaser')">
					<span class="required-sign">*</span>采购员
				</template>
				<template slot-scope="scope">
					<user-select   v-model="scope.row.purchaser"  placeholder="请选择"   :disabled="judgeWrite('gyplanbList') || judgeWrite('gyplanbList-purchaser')"    clearable >
				</user-select>
		</template>
		</el-table-column>
			<el-table-column prop="materialfile" label="物料附件"   v-if="judgeShow('gyplanbList-materialfile')"  >
				<template slot="header" v-if="judgeRequired('gyplanbList-materialfile')">
					<span class="required-sign">*</span>物料附件
				</template>
				<template slot-scope="scope">
					<el-input   v-model="scope.row.materialfile"  placeholder="请输入"   :disabled="judgeWrite('gyplanbList') || judgeWrite('gyplanbList-materialfile')"    clearable  :style='{"width":"100%"}'>
				</el-input>
		</template>
		</el-table-column>
			<el-table-column prop="supplierfile" label="供应商附件"   v-if="judgeShow('gyplanbList-supplierfile')"  >
				<template slot="header" v-if="judgeRequired('gyplanbList-supplierfile')">
					<span class="required-sign">*</span>供应商附件
				</template>
				<template slot-scope="scope">
					<el-input   v-model="scope.row.supplierfile"  placeholder="请输入"   :disabled="judgeWrite('gyplanbList') || judgeWrite('gyplanbList-supplierfile')"    clearable  :style='{"width":"100%"}'>
				</el-input>
		</template>
		</el-table-column>
						<el-table-column label="操作" width="50" v-if="!setting.readonly && !judgeWrite('gyplanbList')" >
							<template slot-scope="scope">
								<el-button size="mini" type="text" class="JNPF-table-delBtn" @click="delgyplanbList(scope.$index)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
					<div class="table-actions" @click="addgyplanbList()">
						<el-button type="text" icon="el-icon-plus">添加</el-button>
					</div>
	</el-form-item>
	</el-col>
			</template>
		</el-form>
		</el-row>
		<UserBox v-if="userBoxVisible" ref="userBox" @submit="submit" />
	</div>
</template>
<script>
	import request from '@/utils/request'
	import { getDataInterfaceRes } from '@/api/systemData/dataInterface'
	import { getDictionaryDataSelector } from '@/api/systemData/dictionary'
	export default {
        components: {},
		props: [],
		data() {
			return {
				visible: false,
				loading: false,
				setting:{},
				eventType: '',
				userBoxVisible:false,
                currTableConf:{},
                addTableConf:{
                        gyplanbList :{"popupType":"dialog","hasPage":true,"popupTitle":"选择数据","pageSize":20,"columnOptions":[],"interfaceId":"","interfaceName":"","relationOptions":[],"templateJson":[],"popupWidth":"800px"},
                },
				tableRows:{
							gyplanbList:{
									zid : '',
									material : '',
									supplier : '',
									number : '',
									price : '',
									money : '',
									needtime : '',
									plannum : '',
									materialfile : '',
									supplierfile : '',
								enabledmark:undefined
						}
				},
				dataForm: {
					id:'',
					flowId: '',
					status: 1,
					freeapproveruserid: '',
					flowUrgent:1,
									code : undefined,
										billdate : undefined,
										billmaker : undefined,
										status : "-1",
									approver : undefined,
									approvetime : undefined,
									attachment : [],
										creatoruserid : undefined,
										creatortime : undefined,
										lastmodifyuserid : undefined,
										lastmodifytime : undefined,
					gyplanbList:[],
            },
			tableRequiredData: {},
				dataRule:
            {



                                purchaser: [
                                    {
                                        required: true,
                                        message: '请选择',
                                        trigger: 'click'
                                    },
                            ],

            },
                        statusOptions:[{"fullName":"自由","id":"-1"},{"fullName":"审批通过","id":"1"}],

                        gyplanbmaterialcolumnOptions:[ {"label":"物料名称","value":"F_MatName"}, {"label":"物料编码","value":"F_MatCode"}, {"label":"规格型号","value":"F_MatSpec"},],
                        gyplanbsuppliercolumnOptions:[ {"label":"供应商编码","value":"F_Code"}, {"label":"供应商名称","value":"F_Name"},],
                        gyplanbplannumcolumnOptions:[ {"label":"实施计划号","value":"F_PlanCode"}, {"label":"物料编码","value":"F_MatCode"}, {"label":"物料名称","value":"F_MatName"}, {"label":"规格型号","value":"F_MatSpec"},],
			}
		},
		computed: {
			formOperates() {
				return this.setting.formOperates
			}
		},
        watch: {},
		created() {
        },
		mounted() {},
		methods: {
			judgeShow(id) {
				if (!this.setting.formOperates || !this.setting.formOperates.length) return true
				let arr = this.setting.formOperates.filter(o => o.id === id) || []
				if (!arr.length) return true
				let item = arr[0]
				return item.read
			},
			judgeWrite(id) {
				if (!this.setting.formOperates || !this.setting.formOperates.length) return false
				let arr = this.setting.formOperates.filter(o => o.id === id) || []
				if (!arr.length) return true
				let item = arr[0]
				return !item.write
			},
                goBack() {
                    this.$emit('refresh')
                },
            init(data) {
                this.dataForm.id = data.id || "";
				this.setting = data;
                this.visible = true;
				this.updateDataRule()
                this.$nextTick(() => {
                    this.$refs['elForm'].resetFields();
                    if(this.dataForm.id){
                        this.loading = true
                        request({
                            url: '/api/example/GyPlan/'+this.dataForm.id,
                            method: 'get'
                        }).then(res => {
                            this.dataInfo(res.data)
                            this.loading = false
                        })
                    }
					this.$emit('setPageLoad')
                })
				this.$store.commit('generator/UPDATE_RELATION_DATA', {})
            },
			updateDataRule() {
				let newRules = {}
				for (let i = 0; i < this.setting.formOperates.length; i++) {
					const item = this.setting.formOperates[i]
					if (!item.id.includes('-')) {
						const newRulesItem = {
							required: item.required,
							message: item.name + '不能为空',
							trigger: item.trigger || 'blur'
						}
						if (!this.dataRule.hasOwnProperty(item.id)) {
							if (item.required) this.$set(newRules, item.id, [newRulesItem])
						} else {
							let withoutRequiredItem = true
							for (let i = 0; i < this.dataRule[item.id].length; i++) {
								if (this.dataRule[item.id][i].hasOwnProperty('required')) {
									this.dataRule[item.id][i].required = item.required
									withoutRequiredItem = false
								}
							}
							if (withoutRequiredItem && item.required) this.dataRule[item.id].push(newRulesItem)
						}
					} else {
						let key = item.id.split('-')[0]
						let newId = item.id.split('-')[1]
						let newItem = {
							...item,
							id: newId
						}
						if (!this.tableRequiredData.hasOwnProperty(key)) {
							this.$set(this.tableRequiredData, key, [newItem])
						} else {
							this.tableRequiredData[key].push(newItem)
						}
					}
				}
				this.dataRule = { ...this.dataRule, ...newRules }
			},
			exist() {
				let isOk = true
				for (let key in this.tableRequiredData) {
					if (this.dataForm[key] && Array.isArray(this.dataForm[key])) {
						for (let i = 0; i < this.dataForm[key].length; i++) {
							let item = this.dataForm[key][i]
							inner: for (let id in item) {
								let arr = this.tableRequiredData[key].filter(o => o.id === id) || []
								if (!arr.length) continue inner
								if (arr[0].required) {
									let msg = `${arr[0].name}不能为空`
									let boo = true
									if (arr[0].dataType === 'array') {
										boo = !this.jnpf.isEmptyArray(item[id])
									} else {
										boo = !this.jnpf.isEmpty(item[id])
									}
									if (!boo) {
										this.$message({
											message: msg,
											type: 'error',
											duration: 1000
										})
										isOk = false
										break
									}
								}
							}
						}
					}
				}
				return isOk
			},
			judgeRequired(id) {
				if (!this.formOperates || !this.formOperates.length) return false
				let arr = this.formOperates.filter(o => o.id === id) || []
				if (!arr.length) return false
				let item = arr[0]
				return item.required
			},
            // 表单提交
            dataFormSubmit(eventType,flowUrgent) {
                this.$refs['elForm'].validate((valid) => {
					if (valid) {
						if (this.exist && !this.exist()) return
						if (eventType === 'audit' || eventType === 'reject') {
							this.$emit('eventReceiver', this.dataForm, eventType)
							return
						}
						this.dataForm.status = eventType === 'submit' ? 0 : 1
						this.dataForm.flowId=this.setting.flowId
						this.dataForm.flowUrgent = flowUrgent
						this.eventType = eventType
						if (this.eventType === 'submit') {
							this.$confirm('您确定要提交当前流程吗, 是否继续?', '提示', {
								type: 'warning'
							}).then(() => {
								this.request()
							}).catch(() => { });
						} else {
							this.request()
						}
					}
                })
            },
            request() {
                var _data =this.dataList()
                if (!this.dataForm.id) {
                    request({
                        url: '/api/example/GyPlan',
                        method: 'post',
                        data: _data
                    }).then((res) => {
                        this.$message({
                            message: res.msg,
                            type: 'success',
                            duration: 1000,
                            onClose: () => {
                                this.visible = false
								this.$emit('close', true)
                            }
                        })
                    })
                }else{
                    request({
                        url: '/api/example/GyPlan/'+this.dataForm.id,
                        method: 'PUT',
                        data: _data
                    }).then((res) => {
                        this.$message({
                            message: res.msg,
                            type: 'success',
                            duration: 1000,
                            onClose: () => {
                                this.visible = false
								this.$emit('close', true)
                            }
                        })
                    })
                }
            },
                addgyplanbList(){
                    let item = {
							zid:undefined,
							material:undefined,
							supplier:undefined,
							number:undefined,
							price:undefined,
							money:undefined,
							needtime:undefined,
							userman:undefined,
							userdept:undefined,
							plannum:undefined,
							purchaser:undefined,
							materialfile:undefined,
							supplierfile:undefined,
                }
                    this.dataForm.gyplanbList.push(item)
                },
                delgyplanbList(index) {
                    this.dataForm.gyplanbList.splice(index, 1);
                },
            openSelectDialog(key) {
                this.currTableConf=this.addTableConf[key]
                this.currVmodel=key
                this.selectDialogVisible = true
                this.$nextTick(() => {
                    this.$refs.selectDialog.init()
                })
            },
            addForSelect(data) {
                for (let i = 0; i < data.length; i++) {
                    let item={...this.tableRows[this.currVmodel],...data[i]}
                    this.dataForm[this.currVmodel].push(item)
                }
            },
            dataList(){
                var _data = JSON.parse(JSON.stringify(this.dataForm));






        _data.attachment = JSON.stringify(_data.attachment)





                    for(let i=0;i<_data.gyplanbList.length;i++){
                        var _list = _data.gyplanbList[i];
                    }
                return _data;
            },
            dataInfo(dataAll){
                let _dataAll =dataAll
        _dataAll.attachment = JSON.parse(_dataAll.attachment)
                    for(let i=0;i<_dataAll.gyplanbList.length;i++){
                        var _list = _dataAll.gyplanbList[i];
                    }
                this.dataForm = _dataAll
            },
        },
    }

</script>
